import smtplib
import email.utils
from email.mime.text import MIMEText
import string

import sys

from typing import List

from alibabacloud_dysmsapi20170525.client import Client as Dysmsapi20170525Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_dysmsapi20170525 import models as dysmsapi_20170525_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_tea_util.client import Client as UtilClient

import random


class EmailSender:
    def generate_verification_code(self, length=4):
        """生成指定长度的验证码，仅包含数字"""
        letters_and_digits = string.digits
        return ''.join(random.choice(letters_and_digits) for i in range(length))

    def send_verification_code(self, receiver_email):
        """发送验证码邮件"""
        smtp_server = "smtp.qq.com"
        smtp_port = 465
        sender_email = "2427754609@qq.com"
        sender_password = "imgrrxqdujzyecjc"

        verification_code = self.generate_verification_code()
        message = MIMEText(f"您的验证码是: {verification_code}")
        message["From"] = email.utils.formataddr((sender_email, sender_email))
        message["To"] = email.utils.formataddr(('用户', receiver_email))
        message["Subject"] = '中软杯'

        try:
            smtp_obj = smtplib.SMTP_SSL(smtp_server, smtp_port)
            smtp_obj.login(sender_email, sender_password)
            smtp_obj.sendmail(sender_email, [receiver_email], msg=message.as_string())
            print("邮箱 code sent successfully.")
            return verification_code
        except Exception as e:
            print(f"Failed to send verification code: {e}")
        finally:
            smtp_obj.quit()

class Sample:
    def __init__(self):
        pass

    @staticmethod
    def create_client() -> Dysmsapi20170525Client:
        """
        使用AK&SK初始化账号Client
        @return: Client
        @throws Exception
        """
        config = open_api_models.Config(
            # 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。,
            access_key_id='LTAI5tSHbGaLVxrJHZb7JCC5',
            # 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。,
            access_key_secret='GQOapLPl734jspbwQI43iOXHrjkQ6Q'
        )
        # Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
        config.endpoint = f'dysmsapi.aliyuncs.com'
        return Dysmsapi20170525Client(config)

    @staticmethod
    def main(
        args: List[str],number
    ) -> None:
        client = Sample.create_client()
        # 生成随机验证码
        code = str(random.randint(1000, 9999))
        send_sms_request = dysmsapi_20170525_models.SendSmsRequest(
            sign_name='中软杯',
            template_code='SMS_468105006',
            phone_numbers=number,
            template_param=f'{{"code":"{code}"}}'
        )
        runtime = util_models.RuntimeOptions()
        try:
            # 复制代码运行请自行打印 API 的返回值
            client.send_sms_with_options(send_sms_request, runtime)
            print("短信验证码发送成功")
            return code
        except Exception as error:
            # 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            # 错误 message
            print(error.message)
            # 诊断地址
            print(error.data.get("Recommend"))
            UtilClient.assert_as_string(error.message)

if __name__ == '__main__':
    number_code = Sample.main(sys.argv[1:],'13786622751')
    # sender = EmailSender()
    # mail_code = sender.send_verification_code('13786622751@163.com')
    print(number_code)